require "digest/sha1"
class User < ActiveRecord::Base
  
  has_one :profile
  has_one :active_users, :conditions=>"user_id!=0"
  
  has_many :log,:class_name=>"sb_log"
  has_many :upload_pictures, :class_name=>"Picture", :foreign_key => "user_id"
  has_many :friends
  has_many :incumbents, :conditions=>"deleted=0"
  has_many :reports
  has_many :companies
  has_many :comments
  has_many :topics
  has_many :inbox_messages, :class_name=>"Message::InboxMessage", :foreign_key => "user_id" #Receive, inbox
  has_many :outbox_messages, :class_name=>"Message::OutboxMessage", :foreign_key => "user_id"  #Send, outbox
  
  belongs_to :user_group, :class_name=>"UserGroup"
  belongs_to :picture, :foreign_key =>"picture_id"
  
  attr_accessor :password_confirmation
  attr_accessible :name, :password, :password_confirmation, :email, :image_url, :create_ip, :search_tag
  
  def age
    return Time.now.year-profile.birthday.year
  end
  
  def experience
    return profile.experience.to_i
  end
  
  def sex
    return profile.sex
  end
  
  def birthday
    return profile.birthday
  end
  
  def report_age(year)
    return year-profile.birthday.year
  rescue
    return 0
  end
  
  def report_experience(year)
    return year-profile.experience.to_i
  rescue
    return 0
  end
  
  def report_sex
    return profile.sex
  end
  
  def report_education
    return profile.report_education
  end
  
  def tag_list
    return Index.show_tag_list(self)
  end
  
  def report_oversea
    return profile.report_oversea
  end
  
  def before_create
    self.anonymous=0
    self.picture_id=1
    self.deleted=0
    self.password = User.hash_password(self.password)
    self.created_at=Time.now
    self.banned_to=Time.now
    self.search_tag<< " "  unless self.search_tag==""
    self.create_search_tag
  end
  
  def after_create
    Index.index_search_tag(self)
  end
  
  def reindex_search_tag
    self.search_tag<< " "  unless self.search_tag==""
    self.create_search_tag
    Index.clear_search_tag(self)
    Index.index_search_tag(self)
    self.save
  end
  
  def create_query_conditions(query,category_id,additional_conditions="")
    Keyword.create_query_conditions(query,self,category_id,additional_conditions)
  end
  
  def create_company(params)
    new_company=Company.new(params)
    new_company.user=self
    new_company.save
    return new_company
  end
  
  def create_incumbent(params,company)
    new_incumbent=Incumbent.new(params)
    new_incumbent.view_company=company
    new_incumbent.incumbent_evaluation=IncumbentEvaluation.new
    new_incumbent.user=self
    new_incumbent.created_ip=self.login_ip
    new_incumbent.updated_ip=self.login_ip
    new_incumbent.save
    return new_incumbent
  end
  
  def create_topic(params,forum)
    new_topic=Topic.new(params)
    new_topic.user_id= self.id
    new_topic.forum_id = forum.id
    if new_topic.save
      forum.add_topic(new_topic)
    end
    return new_topic
  end
  
  def create_picture(params,cat_id,obj_id)
    unless self.guest?
      new_picture = Picture.new(params)
      new_picture.uploader = self
      obj=Category.find_object(obj_id,cat_id)  
      obj.picture=new_picture if self.own(obj)
      if new_picture.save && obj.save
        return new_picture
      else
        return false
      end
    else
      return false
    end
  rescue
    return false
  end
  
  def create_outbox_message(mgser_id)
    message=Message.new(:title=>"来自"+self.name+"的问候")
    message.user_id=self.id
    message.mgser_id=mgser_id
    return message
  end
  
  def create_message(mgser_id,params)
    if mgser=User.find_by_id_and_usergroup_id(mgser_id,1)
      self.outbox_messages<<Message::OutboxMessage.create(:title=>params[:title],:body=>params[:body],:mgser_id=>mgser_id,:new_mgs=>0)
      mgser.inbox_messages<<Message::InboxMessage.create(:title=>params[:title],:body=>params[:body],:mgser_id=>self.id)
      return "消息发送成功"
    else
      return "查无此人"
    end
  end
  
  def create_friend(friend_id)
    if Friend.find_by_user_id_and_friend_id(self.id,user.id)==nil
      friendship = Friend.new
      friendship.friend=User.find_by_id_and_usergroup_id(friend_id,1)
      friendship.user=self
      friendship.save
      return friendship.friend
    else
      return nil
    end
  rescue
    return nil
  end
  
  def remember_me
     if self.remember_token.nil?
        self.remember_token = Digest::SHA1.hexdigest("#{self.name}--#{self.login_ip}--#{Time.now}")
     end
  end

  def forget_me
     self.remember_token = nil
  end
  
  def delete_picture(id)
    picture = Picture.find_by_id(id)
    if self.own(picture)
      picture.destroy
      return true
    else
      return false
    end
  end
  
  def update_topic(params,topic)
    if self.own(topic)
      topic.body=params[:body]
      topic.title=params[:title]
      topic.updated_at= Time.now
      topic.reindex_search_tag
      if topic.save && forum=Forum.find(topic.forum_id)
        forum.update_forum(self)
      end
    end
    return topic
  end
  
  def create_comment(params,obj,user_ip)
    new_comment=Comment.new(params)
    new_comment.created_at= Time.now
    new_comment.created_ip= user_ip
    new_comment.user_id= self.id
    new_comment.obj_id = obj.id
    new_comment.category = Category.find_category(obj)
    if new_comment.save
      obj.reply_times += 1 
      obj.updated_at = Time.now
      obj.save
    end
    return new_comment
  end
  
  def update_comment(params,comment)
    if self.own(comment)
      comment.body=params[:body]
      comment.title=params[:title]
      comment.save
    end
    return comment
  end
  
  def delete_incumbent(incumbent_id)
    if incumbent = Incumbent.find(:first,:conditions=>["deleted=0 and user_id=? and id=?",self.id,incumbent_id])
      if self.incumbents_count>1
        incumbent.kill()
        return true
      else
        return false
      end 
      return false 
    end
  end
  
  def delete_company(company_id)
    return false
  end
  
  def update_tag(obj,search_tag)
    if search_tag.length<50
      if self.own(obj)
        obj.search_tag=search_tag
        if obj.save
          obj.reindex_search_tag
          return "标签已经重新索引了"
        else
          return "对不起，你无权更新标签"
        end
      else
        return "对不起，你无权更新标签"
      end
    else
      return "输入标签过多，更新失败"
    end
  end
  
  def update_user(params)
    validation=User.validate_update_params(params)
    if validation.length==0
      self.email=params[:email]
      self.msn=params[:msn]
      self.blog=params[:blog]
      self.comment=params[:comment]
      self.anonymous=params[:anonymous]
      if self.save
        return nil
      else
        return ["<li>权限不足,更新失败</li>"]
      end
    else
      return validation
    end
  rescue
    return ["<li>权限不足,更新失败</li>"]
  end
  
  def update_profile(params)
    validation=Profile.validate_params(params)
    if validation.length==0
      if self.profile.update_fields(params)
        return nil
      else
        return ["<li>权限不足,更新失败</li>"]
      end
    else
      return validation
    end
  end
  
  def self.validate_params(params)
    validation=[]
    validation<<["<li>用户名已经存在了</li>"] if find_by_name(params[:name])
    validation<<["<li>请输入有效的用户名</li>"] unless params[:name]=~/[\d\w]+/&&params[:name].length<20
    validation<<["<li>设置的密码太短</li>"] if params[:password].length<6
    validation<<["<li>确认的密码不正确</li>"] unless params[:password]==params[:password_confirmation]
    validation<<["<li>邮件地址不正确</li>"] unless params[:email]=~/.+@.+\.(com|net|org)/
    return validation
  end
  
  def self.validate_update_params(params)
    validation=[]
    unless params[:msn]==""
      validation<<["<li>MSN账号不正确</li>"] unless params[:msn]=~/.+@.+\.(com|net|org)/&&params[:msn].length<80
    end
    unless params[:email]==""
      validation<<["<li>邮件地址不正确</li>"] unless params[:email]=~/.+@.+\.(com|net|org)/&&params[:email].length<80
    end
    unless params[:blog]==""
      validation<<["<li>请输入有效的博客地址</li>"] unless params[:blog]=~/[\d\w]+/&&params[:blog].length<100
    end
    return validation
  end
  
  def after_login_success(activeuser)
    self.login_at=Time.now
    self.login_ip=activeuser.active_user_ip
    self.save
    activeuser.user=self
    activeuser.save
  end
  
  def try_to_login
    User.login(self.name, self.password)
  end
  
  def logout
    self.ol_time=(Time.now - self.login_at).second
    self.save
  end
  
  def banned?
    Time.now<self.banned_to ? true : false
  end
  
  def guest?
    return self.id == GUEST_USER_ID
  end
  
  def adminstrative?
    self.administrative==1 ? true : false
  end
  
  def own(obj)
    if self.guest?
      return false
    else
      validate_id = obj.class.name=="User" ? obj.id : obj.user_id 
      return self.id==validate_id ? true : false
    end
  rescue
    return false
  end
  
  def update_password(old_pw,new_pw,confirm_pw)
    if self.password==User.hash_password(old_pw || "")
      if new_pw==confirm_pw
        if new_pw.length>5
          self.password=User.hash_password(new_pw)
          self.save
          return "密码更新成功"
        else
          return "新密码太短，更新失败"
        end
      else
        return "两次输入的密码不符"
      end
    else
      return "密码错误，更新失败"
    end
  end
  
  def is_friend(user)
    return Friend.find_by_user_id_and_friend_id(self.id,user.id)==nil ? false : true
  end
  
  def log_action(control_name,action_name,obj_id)
    unless self.guest?
      self.pages_view_times+=1
      SbLog.create_log(self,control_name,action_name,obj_id)
      self.save
    end
  end
  
  def self.login(name, password)
    password = hash_password(password || "")
    find(:first,
         :conditions => ["deleted=0 and name = ? and password = ?", 
    name, password])
  end
  
  def create_search_tag
    self.search_tag << self.name unless self.anonymous
  end
  private
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
